import React, { useEffect } from 'react'
import styles from './index.module.scss'
import classNames from 'classnames'
import { useState, useRef } from 'react'

export default function Textarea({
  maxLength = 100,
  value,
  onChange,
  className,
  ...rest
}) {
  const [val, setVal] = useState(value || '')
  const handleChange = (e) => {
    setVal(e.target.value)
    // 如果父组件传了onChange事件
    // 触发父组件的onChange事件 并把当前输入框的值传过去
    onChange && onChange(e)
  }
  const inputRef = useRef(null)
  useEffect(() => {
    inputRef.current.focus()
    inputRef.current.setSelectionRange(-1, -1)
  },[])
  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={inputRef}
        className={classNames('textarea', className)}
        {...rest}
        maxLength={maxLength}
        onChange={handleChange}
        value={val}
      ></textarea>
      {/* 提示信息 */}
      <div className="count">
        {val.length}/{maxLength}
      </div>
    </div>
  )
}
